package cn.szq.concurrent.thread.stop;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: MyBlockingQueueForCondition
 * @Description:
 * @Author: szq
 * @Date: 2021-09-27 10:16:04
 */
public class MyBlockingQueueForCondition {

    private Queue queue;
    private int max;
    private ReentrantLock lock = new ReentrantLock();
    private Condition notEmpty = lock.newCondition();
    private Condition notFull = lock.newCondition();

    public MyBlockingQueueForCondition(int size){
        max = size;
        queue = new LinkedList();
    }

    public void put(Object o) throws InterruptedException{
        lock.lock();
        try{
            while (queue.size() == max){
                notFull.await();
            }
            queue.add(o);
            notEmpty.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try{
            while (queue.size() == 0){
                notEmpty.await();
            }
            Object o = queue.remove();
            notFull.signalAll();
            return o;
        }finally {
            lock.unlock();
        }
    }


}
